// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num: 1,
    shopping: [],
    totalPrice: 0,
    totalNum: 0,
    allChecked: false
  },
  async onChange(e) {

    let operation = e.detail
    let {
      id
    } = e.currentTarget.dataset;
    let {
      shopping
    } = this.data;
    let index = shopping.findIndex(v => v.goods_id === id);
    if (shopping[index].num === 1 && operation === -1) {
      let res = await showModal({
        content: "您是否要删除？"
      });
      if (res.confirm) {
        shopping.splice(index, 1);
        this.setCart(shopping);
      }
    } else {
      shopping[index].num = operation;
      this.setCart(shopping);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let shopping = wx.getStorageSync('shopping')
    this.setData({
      shopping
    })

  },
  // 商品的选中
  handeItemChange(e) {
    const goods_id = e.currentTarget.dataset.id;
    let {
      shopping
    } = this.data;
    let index = shopping.findIndex(v => v.goods_id === goods_id);
    shopping[index].checked = !shopping[index].checked;
    this.setCart(shopping);
  },
  setCart(cart) {
    let allChecked = true;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      } else {
        allChecked = false;
      }
    })
    allChecked = cart.length != 0 ? allChecked : false;
    this.setData({
      shopping: cart,
      totalPrice,
      totalNum,
      allChecked
    });
    wx.setStorageSync("shopping", cart);
  },
  handleItemAllCheck() {
    let {
      shopping,
      allChecked
    } = this.data;
    allChecked = !allChecked;
    shopping.forEach(v => v.checked = allChecked);
    this.setCart(shopping);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})